package com.itcast.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.itcast.constant.RedisConstant;
import com.itcast.dao.CheckItemDao;
import com.itcast.dao.CheckgroupDao;
import com.itcast.dao.SetmealDao;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.pojo.CheckGroup;
import com.itcast.pojo.CheckItem;
import com.itcast.pojo.Order;
import com.itcast.pojo.Setmeal;
import com.itcast.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐管理
 */
@Service(interfaceClass = SetmealService.class)

@Transactional
public class SetmealServiceImpl  implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private CheckgroupDao checkgroupDao;

    @Autowired
    private CheckItemDao checkItemDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${OutPutPath}")
    private String OutPutPath;
    /**
     * 添加套餐
     */
    @Override
    public Integer add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if (checkgroupIds!=null&&checkgroupIds.length>0){

        addSetmealAndCheckgroup(checkgroupIds, setmealId);

        }
        addredies(setmeal.getImg());
        return setmealId;
    }
    public void genneratSetmealHtml(int setmealId){
        Setmeal setmeal1 = findById(setmealId);
//        只生成一个页面
        List<Setmeal> detailList =new ArrayList<>();
        detailList.add(setmeal1);
        //生成套餐静态页面
        generaStaticSetmealAllHtml(findAll());
        //生成套餐详情静态页面
        generaStaticSetmealDetailHtml(detailList);
    }

    /**
     * 查找套餐名和预约人数
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    private void addredies(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

    /**
     * 抽取添加套餐和检查组关系
     * @param checkgroupIds
     * @param setmealId
     */
    private void  addSetmealAndCheckgroup(Integer[] checkgroupIds, Integer setmealId) {
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addCheckgroupAndSetmeal(checkgroupId,setmealId);

        }
    }


    /**
     * 分页查询功能
     * @param queryPageBean
     * @return 返回分页查询数据
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean){
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (queryString!=null){
            queryString = queryString.trim();
            if (queryString.length()>0 && !"null".equalsIgnoreCase(queryString)){
                queryString="%"+queryString+"%";
            }else {
                queryString= null;

            }

        }
        Page<Setmeal> setmealPage = setmealDao.findPage(queryString);
        long total = setmealPage.getTotal();
        return new PageResult(total,setmealPage);
    }


    /**
     * 查询所有套餐信息
     * @return 返回套餐集合
     */
    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }


    /**
     * 查询套餐详情
     * 使用list集合查询，减少数据库访问次数
     * @param id
     * @return  返回setmeal对象，完整包含套餐所有信息
     */
    @Override
    public Setmeal findById(int id) {
        Setmeal setmeal = setmealDao.findById(id);
        List<Integer> CheckGroupIds = checkgroupDao.findByCheckGroupIds(id);
        if (CheckGroupIds!=null&&CheckGroupIds.size()>0){
        List<CheckGroup> checkGroups = checkgroupDao.findByIds(CheckGroupIds);
        for (CheckGroup checkGroup : checkGroups) {
            Integer checkGroupId = checkGroup.getId();
            List<Integer> checkitemIds = checkgroupDao.findByCheckitemIds(checkGroupId);
            if (checkitemIds!=null&&checkitemIds.size()>0) {
                List<CheckItem> checkItems = checkItemDao.findByIds(checkitemIds);
                checkGroup.setCheckItems(checkItems);
            }
        }
        setmeal.setCheckGroups(checkGroups);
        }

        //数据库查询次数太多
        /*List<CheckGroup> checkGroups = new ArrayList<>();
        for (Integer checkGroupId : CheckGroupIds) {
            CheckGroup checkGroup = checkgroupDao.fingById(checkGroupId);
            List<Integer> checkitemIds = checkgroupDao.findByCheckitemIds(checkGroupId);
            List<CheckItem> checkItems= new ArrayList<>();
            for (Integer checkitemId : checkitemIds) {
                CheckItem checkItem = checkItemDao.findByid(checkitemId);
                checkItems.add(checkItem);
            }
            checkGroup.setCheckItems(checkItems);
            checkGroups.add(checkGroup);
            setmeal.setCheckGroups(checkGroups);
        }*/
       return setmeal;
    }


    /**
     * 生成套餐静态页面
     * @param lis
     *
     * 抽取通用service来避免service互相调用
     * findById   生成套餐页面
     */
    public void generaStaticSetmealAllHtml(List<Setmeal> lis){
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList",lis);
        generatHtml("mobile_setmeal.ftl",OutPutPath+"setmeal.html",map);
    }

    public void generaStaticSetmealDetailHtml(List<Setmeal> lis){


        for (Setmeal setmeal : lis) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal",setmeal);
            generatHtml("mobile_setmeal_detail.ftl",OutPutPath+"setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }
    /**
     * 生成静态页面的通用方法
     * @param tempalteFileName
     * @param GeneratHtmlName
     * @param map
     */
    private void generatHtml(String tempalteFileName , String GeneratHtmlName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate(tempalteFileName);
            FileWriter fileWriter = new FileWriter(new File( GeneratHtmlName));
            template.process(map,fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
